<template>
  <div style="text-align: center;">
    <div>
      <div style="font-size: 40px;">登录</div>
    </div>
    <div style="margin-top: 50px;">
      <el-input
        v-model="form.username"
        type="text"
        style="font-size: 24px; height: 40px;"
        placeholder="账号/邮箱"
      >
        <template #prefix>
          <el-icon>
            <User />
          </el-icon>
        </template>
      </el-input>
      <el-input
        v-model="form.password"
        type="password"
        style="font-size: 24px; height: 40px; margin-top: 10px"
        placeholder="密码"
      >
        <template #prefix>
          <el-icon>
            <Lock />
          </el-icon>
        </template>
      </el-input>
    </div>
    <el-row style="margin-top: 5px">
      <el-col
        :span="12"
        style="text-align: left;"
      >
        <el-checkbox
          v-model="form.remember"
          label="记住我"
        ></el-checkbox>
      </el-col>
      <el-col
        :span="12"
        style="text-align: right"
      >
        <el-link @click="router.push('/forget')">忘记密码？</el-link>
      </el-col>
    </el-row>
    <div style="margin-top: 40px">
      <el-button
        @click="login()"
        style="width: 300px;font-size: 20px"
        type="success"
        plain
      >立即登录</el-button>
    </div>
    <el-divider>
      <span style="color: grey; font-size: 16px">没有账号</span>
    </el-divider>
    <div>
      <el-button
        style="width: 300px;font-size: 20px"
        @click="router.push('/register')"
        type="warning"
        plain
      >注册账号</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { ElMessage } from "element-plus";
import { get, post } from "@/net";
import router from "@/router";
import { useAccountStore } from "@/store";
import { useAuthStore } from "@/store";
const store = useAccountStore();
const authStore = useAuthStore();
const form = reactive({
  username: "",
  password: "",
  remember: false,
});

const login = () => {
  if (!form.username || !form.password) {
    ElMessage.warning("请填写账号和密码！");
  } else {
    post(
      "/account/login",
      {
        id: form.username,
        pwd: form.password,
        remember: form.remember,
      },
      (message) => {
        ElMessage.success("登录成功");//message.msg
        authStore.setToken(message.data.accessToken);
        get(
          "/account/get_info", { id: form.username },
          (message) => {
            ElMessage.success("获取成功");
            store.setAccount(message.data);
            router.push("/mybox"); //登录成功后跳转到首页
          },
          () => {
            store.clearAccount();
          }
        );
      },
      (message) => {
        ElMessage.error(message.msg);
        store.clearAccount();
      }
    );
  }
};
</script>

<style scoped>
</style>
